﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;

namespace FreeDict
{
    public class FreeDictionary
    {
        private readonly Dictionary<string, string> _data = new Dictionary<string, string>();
        private ILookup<char, string> _index;

        public int GetWordCount()
        {
            return _data.Count;
        }

        public IEnumerable<string> GetWords()
        {
            return _data.Keys;
        }

        public string GetTranslation(string word)
        {
            if (string.IsNullOrEmpty(word))
                return null;

            string result;
            return _data.TryGetValue(word.ToLower(), out result) ? result : null;
        }

        public string FindWord(string startsWith)
        {
            if (string.IsNullOrEmpty(startsWith) || _index == null)
                return null;

            startsWith = startsWith.ToLower();
            return _index[startsWith[0]].FirstOrDefault(w => w.StartsWith(startsWith));
        }

        public async Task LoadAsync(string fileName)
        {
            //await Task.Delay(3000);
            
            var file = await Package.Current.InstalledLocation.GetFileAsync(fileName);
            using (var sr = new StreamReader(await file.OpenStreamForReadAsync()))
            {
                while (true)
                {
                    var nextLine = await sr.ReadLineAsync();
                    if (nextLine == null)
                        break;

                    if (string.IsNullOrWhiteSpace(nextLine))
                        continue;

                    var delimIndex = nextLine.IndexOf("  ", StringComparison.Ordinal);
                    if (delimIndex < 0)
                        continue;

                    var word = nextLine.Substring(0, delimIndex).ToLower();
                    if (string.IsNullOrWhiteSpace(word))
                        continue;

                    var translation = nextLine.Substring(delimIndex + 2);
                    _data[word] = translation;
                }
            }

            // Build index
            await Task.Run(() =>
                               {
                                   _index = _data.Keys.ToLookup(s => s[0], s => s);
                               });
        }
    }
}